package com.gitee.shigen.gateway.fliter;

import static org.springframework.cloud.gateway.filter.WebClientWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER;

import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

/**
 * 生成日志唯一ID，并放到请求头信息中，以及集成slf4j
 *
 * @author shigenfu
 */
@Component
@Slf4j
public class TraceInfoFilter implements GlobalFilter, Ordered {

    private static final String TRACE_ID = "traceId";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 打印日志，表示过滤器开始执行
        log.info("====== TraceInfoFilter start ======");
        HttpHeaders headers = exchange.getRequest().getHeaders();
        String traceId = headers.getFirst(TRACE_ID);
        if (StrUtil.isNotEmpty(traceId)) {
            // 如果请求头中已经包含traceId，则直接使用现有的traceId
            MDC.put(TRACE_ID, traceId);
        } else {
            // 生成新的traceId并设置到请求头中
            traceId = IdUtil.nanoId(10);
            ServerHttpRequest request = exchange.getRequest().mutate().header(TRACE_ID, traceId).build();
            MDC.put(TRACE_ID, traceId);
            // 打印debug级别的日志，记录生成的traceId
            log.info("Generated traceId: {}", traceId);
            // 使用mutate方法更新当前的exchange对象
            exchange = exchange.mutate().request(request).build();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return WRITE_RESPONSE_FILTER_ORDER - 2;
    }
}
